package com.example.remotecontrol.ui.devices

import android.Manifest
import android.bluetooth.BluetoothDevice
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.Cable
import androidx.compose.material.icons.filled.Cast
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.data.model.DeviceType
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.MultiplePermissionsState
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import java.net.InetAddress

/**
 * 设备发现界面
 * 支持蓝牙、WiFi和红外设备的自动发现
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalPermissionsApi::class)
@Composable
fun DeviceDiscoveryScreen(
    viewModel: DeviceDiscoveryViewModel = hiltViewModel(),
    onClose: () -> Unit,
    onAddDevice: (Device) -> Unit
) {
    // 需要的权限列表
    val bluetoothPermissions = rememberMultiplePermissionsState(
        listOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    )
    
    val wifiPermissions = rememberMultiplePermissionsState(
        listOf(
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    )
    
    // UI状态
    val deviceDiscoveryState by viewModel.deviceDiscoveryState.collectAsState()
    val bluetoothDevices by viewModel.bluetoothDevices.collectAsState()
    val wifiDevices by viewModel.wifiDevices.collectAsState()
    val scanningBluetooth by viewModel.scanningBluetooth.collectAsState()
    val scanningWifi by viewModel.scanningWifi.collectAsState()
    
    // 当前选择的发现方式
    var selectedDiscoveryType by remember { mutableStateOf(DiscoveryType.ALL) }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("发现设备") },
                navigationIcon = {
                    IconButton(onClick = onClose) {
                        Icon(
                            imageVector = Icons.Default.Close,
                            contentDescription = "关闭"
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
        ) {
            // 扫描类型选择
            DiscoveryTypeSelector(
                selectedType = selectedDiscoveryType,
                onTypeSelected = { selectedDiscoveryType = it }
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 扫描进度指示器
            if (scanningBluetooth || scanningWifi) {
                LinearProgressIndicator(
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "正在扫描设备，请稍候...",
                    style = MaterialTheme.typography.bodyMedium,
                    textAlign = TextAlign.Center,
                    modifier = Modifier.fillMaxWidth()
                )
                
                Spacer(modifier = Modifier.height(16.dp))
            }
            
            // 扫描按钮行
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                // 蓝牙扫描按钮
                if (selectedDiscoveryType == DiscoveryType.ALL || selectedDiscoveryType == DiscoveryType.BLUETOOTH) {
                    ScanButton(
                        icon = Icons.Default.Bluetooth,
                        text = "扫描蓝牙设备",
                        isScanning = scanningBluetooth,
                        permissionsState = bluetoothPermissions,
                        onScanClick = { viewModel.startBluetoothDiscovery() },
                        modifier = Modifier.weight(1f)
                    )
                    
                    Spacer(modifier = Modifier.width(8.dp))
                }
                
                // WiFi扫描按钮
                if (selectedDiscoveryType == DiscoveryType.ALL || selectedDiscoveryType == DiscoveryType.WIFI) {
                    ScanButton(
                        icon = Icons.Default.Wifi,
                        text = "扫描WiFi设备",
                        isScanning = scanningWifi,
                        permissionsState = wifiPermissions,
                        onScanClick = { viewModel.startWifiDiscovery() },
                        modifier = Modifier.weight(1f)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 设备列表
            LazyColumn(
                modifier = Modifier.weight(1f)
            ) {
                // 蓝牙设备
                if ((selectedDiscoveryType == DiscoveryType.ALL || selectedDiscoveryType == DiscoveryType.BLUETOOTH) && 
                    bluetoothDevices.isNotEmpty()) {
                    
                    item {
                        Text(
                            text = "蓝牙设备",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(vertical = 8.dp)
                        )
                    }
                    
                    items(bluetoothDevices) { device ->
                        BluetoothDeviceItem(
                            device = device,
                            onAddDevice = { 
                                val newDevice = Device(
                                    id = device.address,
                                    name = device.name ?: "未知设备",
                                    brand = "未知",
                                    model = device.address,
                                    room = "",
                                    type = DeviceType.AUDIO,
                                    controlType = Device.ControlType.BLUETOOTH,
                                    controlData = device.address
                                )
                                onAddDevice(newDevice)
                            }
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                    }
                }
                
                // WiFi设备
                if ((selectedDiscoveryType == DiscoveryType.ALL || selectedDiscoveryType == DiscoveryType.WIFI) && 
                    wifiDevices.isNotEmpty()) {
                    
                    item {
                        Text(
                            text = "WiFi设备",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.padding(vertical = 8.dp)
                        )
                    }
                    
                    items(wifiDevices) { device ->
                        WifiDeviceItem(
                            device = device,
                            onAddDevice = { 
                                val newDevice = Device(
                                    id = device.hostAddress,
                                    name = device.hostName ?: "未知设备",
                                    brand = "未知",
                                    model = device.hostAddress,
                                    room = "",
                                    type = DeviceType.TV,
                                    controlType = Device.ControlType.WIFI,
                                    controlData = device.hostAddress
                                )
                                onAddDevice(newDevice)
                            }
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                    }
                }
                
                // 无设备时显示提示
                if (bluetoothDevices.isEmpty() && wifiDevices.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(32.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            if (scanningBluetooth || scanningWifi) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    CircularProgressIndicator()
                                    
                                    Spacer(modifier = Modifier.height(16.dp))
                                    
                                    Text(
                                        text = "正在扫描...",
                                        style = MaterialTheme.typography.bodyLarge
                                    )
                                }
                            } else {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    Icon(
                                        imageVector = Icons.Default.Search,
                                        contentDescription = null,
                                        modifier = Modifier.size(48.dp),
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
                                    )
                                    
                                    Spacer(modifier = Modifier.height(16.dp))
                                    
                                    Text(
                                        text = "未发现设备",
                                        style = MaterialTheme.typography.bodyLarge,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                    
                                    Spacer(modifier = Modifier.height(8.dp))
                                    
                                    Text(
                                        text = "请点击上方按钮开始扫描，或确保设备已开启并在范围内",
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                                        textAlign = TextAlign.Center
                                    )
                                }
                            }
                        }
                    }
                }
            }
            
            // 手动添加设备按钮
            Button(
                onClick = { 
                    onAddDevice(Device(
                        id = "",
                        name = "新设备",
                        brand = "",
                        model = "",
                        room = "",
                        type = DeviceType.TV,
                        controlType = Device.ControlType.IR
                    ))
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = null
                )
                
                Spacer(modifier = Modifier.width(8.dp))
                
                Text("手动添加设备")
            }
        }
    }
}

/**
 * 设备发现类型选择器
 */
@Composable
fun DiscoveryTypeSelector(
    selectedType: DiscoveryType,
    onTypeSelected: (DiscoveryType) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly
    ) {
        DiscoveryTypeButton(
            type = DiscoveryType.ALL,
            icon = Icons.Default.Search,
            label = "全部",
            isSelected = selectedType == DiscoveryType.ALL,
            onClick = { onTypeSelected(DiscoveryType.ALL) }
        )
        
        DiscoveryTypeButton(
            type = DiscoveryType.BLUETOOTH,
            icon = Icons.Default.Bluetooth,
            label = "蓝牙",
            isSelected = selectedType == DiscoveryType.BLUETOOTH,
            onClick = { onTypeSelected(DiscoveryType.BLUETOOTH) }
        )
        
        DiscoveryTypeButton(
            type = DiscoveryType.WIFI,
            icon = Icons.Default.Wifi,
            label = "WiFi",
            isSelected = selectedType == DiscoveryType.WIFI,
            onClick = { onTypeSelected(DiscoveryType.WIFI) }
        )
        
        DiscoveryTypeButton(
            type = DiscoveryType.IR,
            icon = Icons.Default.Cast,
            label = "红外",
            isSelected = selectedType == DiscoveryType.IR,
            onClick = { onTypeSelected(DiscoveryType.IR) }
        )
    }
}

/**
 * 设备发现类型按钮
 */
@Composable
fun DiscoveryTypeButton(
    type: DiscoveryType,
    icon: ImageVector,
    label: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .clip(MaterialTheme.shapes.medium)
            .clickable(onClick = onClick)
            .padding(8.dp)
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(
                    if (isSelected) MaterialTheme.colorScheme.primaryContainer
                    else MaterialTheme.colorScheme.surfaceVariant
                ),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = label,
                tint = if (isSelected) MaterialTheme.colorScheme.primary
                      else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(24.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = if (isSelected) MaterialTheme.colorScheme.primary
                   else MaterialTheme.colorScheme.onSurface
        )
    }
}

/**
 * 扫描按钮
 */
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun ScanButton(
    icon: ImageVector,
    text: String,
    isScanning: Boolean,
    permissionsState: MultiplePermissionsState,
    onScanClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedCard(
        modifier = modifier
            .clickable(
                enabled = !isScanning && permissionsState.allPermissionsGranted,
                onClick = {
                    if (permissionsState.allPermissionsGranted) {
                        onScanClick()
                    } else {
                        permissionsState.launchMultiplePermissionRequest()
                    }
                }
            )
    ) {
        Column(
            modifier = Modifier
                .padding(12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (isScanning) {
                CircularProgressIndicator(
                    modifier = Modifier.size(24.dp),
                    strokeWidth = 2.dp
                )
            } else {
                Icon(
                    imageVector = if (!permissionsState.allPermissionsGranted) Icons.Default.Info else icon,
                    contentDescription = null,
                    tint = if (!permissionsState.allPermissionsGranted) 
                             MaterialTheme.colorScheme.error 
                           else 
                             MaterialTheme.colorScheme.primary
                )
            }
            
            Spacer(modifier = Modifier.height(4.dp))
            
            Text(
                text = if (!permissionsState.allPermissionsGranted) "需要权限" else text,
                style = MaterialTheme.typography.bodySmall,
                textAlign = TextAlign.Center,
                color = if (!permissionsState.allPermissionsGranted) 
                          MaterialTheme.colorScheme.error
                        else
                          MaterialTheme.colorScheme.onSurface
            )
        }
    }
}

/**
 * 蓝牙设备项
 */
@Composable
fun BluetoothDeviceItem(
    device: BluetoothDevice,
    onAddDevice: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 设备图标
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.Bluetooth,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(24.dp)
                )
            }
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 设备信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = device.name ?: "未知设备",
                    style = MaterialTheme.typography.titleMedium
                )
                
                Text(
                    text = device.address,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Text(
                    text = "蓝牙设备",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                )
            }
            
            // 添加按钮
            CircleIconButton(
                icon = Icons.Default.Add,
                onClick = onAddDevice
            )
        }
    }
}

/**
 * WiFi设备项
 */
@Composable
fun WifiDeviceItem(
    device: InetAddress,
    onAddDevice: () -> Unit
) {
    Card(
        modifier = Modifier.fillMaxWidth()
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 设备图标
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.secondaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.Wifi,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.secondary,
                    modifier = Modifier.size(24.dp)
                )
            }
            
            Spacer(modifier = Modifier.width(16.dp))
            
            // 设备信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = device.hostName ?: "未知设备",
                    style = MaterialTheme.typography.titleMedium
                )
                
                Text(
                    text = device.hostAddress,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Text(
                    text = "WiFi设备",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f)
                )
            }
            
            // 添加按钮
            CircleIconButton(
                icon = Icons.Default.Add,
                onClick = onAddDevice
            )
        }
    }
}

/**
 * 圆形图标按钮
 */
@Composable
fun CircleIconButton(
    icon: ImageVector,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colorScheme.primary
) {
    Box(
        modifier = modifier
            .size(40.dp)
            .clip(CircleShape)
            .clickable(onClick = onClick)
            .background(color.copy(alpha = 0.1f)),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = color,
            modifier = Modifier.size(24.dp)
        )
    }
}

/**
 * Icon Button
 */
@Composable
fun IconButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit
) {
    Box(
        modifier = modifier
            .size(48.dp)
            .clickable(onClick = onClick)
            .padding(12.dp),
        contentAlignment = Alignment.Center
    ) {
        content()
    }
}

/**
 * 设备发现类型
 */
enum class DiscoveryType {
    ALL, BLUETOOTH, WIFI, IR
}

/**
 * InetAddress扩展属性
 */
val InetAddress.hostName: String?
    get() = canonicalHostName.takeIf { it != hostAddress } 